﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using TouchRC.Logic;
using TouchRC.MetadataCaching.Extensions;
using System.IO;

namespace TouchRC.Logging
{
    public static class Logger
    {
        public static void LogMessage(string message, params object[] args)
        {
            if (AppSettings.Log)
            {
                string logDir = Path.Combine(ConfigSettings.ProgramDirectory.FullName, "Log");
                FileInfo logFile = new FileInfo(Path.Combine(logDir, AppSettings.ApplicationStartTime.ToString("yyyyMMddHHmm") + ".txt"));
                logFile.Directory.CheckDirectoryCreation();

                StreamWriter logWriter;

                try
                {
                    if (File.Exists(logFile.FullName))
                    {
                        logWriter = new StreamWriter(new FileStream(logFile.FullName, FileMode.Append, FileAccess.Write, FileShare.None));
                    }
                    else
                    {
                        logWriter = new StreamWriter(new FileStream(logFile.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None));
                    }
                }
                catch
                {
                    throw new ApplicationException("Log file locked");
                }

                logWriter.WriteLine(DateTime.Now.ToString() + ": " + string.Format(message, args));
                logWriter.Flush();
                logWriter.Close();
            }
        }
    }
}
